layui.use(['element', 'tree', 'zltreemenu', 'zlContext', 'zlConfig'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , zltreemenu = layui.zltreemenu
        , layer = layui.layer
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , OK = zlConfig.global.result.okState

    var authtree,
        roletree,
        index;

    // 机构区域 目录树渲染
    var orgtreeObj = zltreemenu.render('orgtree', {
        dataurl: layui.cache['contentPath'] + "/manager/coreroleauth/queryOrgddata",
        type: "get",
        tableId: 'tbField',
        isMove: false
    }, {
            onAsyncSuccess: function (event, treeId, treeNode, msg) {
                orgtreeObj.selectNode(orgtreeObj.getNodes()[0]);
                $('#' + orgtreeObj.getNodes()[0].tId + '_a').click();
            },
            onClick: function (event, treeId, treeNode) {
                $('input[name="ORGIDTEMP"]').val(treeNode.RWID);
                roletreerender(treeNode.RWID);
            }
        });
    // 角色树渲染
    function roletreerender(ORGID) {
        // 角色区域 目录树渲染
        roletree = zltreemenu.render('roletree', {
            dataurl: layui.cache['contentPath'] + "/manager/coreroleauth/queryRole?isall=false&ORGID=" + ORGID,
            type: "get",
            isMove: false,
            pIdKey: null,
            search: false,
            dataFilter: function (treeId, parentNode, responseData) {
                if (responseData[statusName] == OK) {
                    var data = responseData[dataName];
                    // 更换图标
                    for (var i = 0; i < data.length; i++) {
                        data[i].icon = layui.cache['contentPath'] + "/static/image/role.png";
                    }
                    return data;
                } else {
                    zlContext.errorMsg(responseData[msgName]);
                }
                return responseData;
            }
        }, {
                onAsyncSuccess: function (event, treeId, treeNode, msg) {
                    roletree.selectNode(roletree.getNodes()[0]);
                    $('#' + roletree.getNodes()[0].tId + '_a').click()
                },
                onClick: function (event, treeId, treeNode) {
                    // 对应角色的数据表格下方权限展示区域 树结构渲染
                    authtree = zltreemenu.render('authtree', {
                        checkEnable: true,
                        autoCheckTrigger: true,
                        chkboxType: { "Y": "ps", "N": "s" },
                        radioType: "all",
                        dataurl: layui.cache['contentPath'] + "/manager/corerightreslevel/query?ORGID=" + $('input[name="ORGIDTEMP"]').val() + "&ROLEID=" + treeNode.RWID,
                        type: "post",
                        idKey: "RESID",
                        search: false,
                        dataFilter: function (treeId, parentNode, responseData) {
                            if (responseData[statusName] == OK) {
                                var data = responseData[dataName];
                                for (var i = 0; i < data.length; i++) {
                                    if (data[i].RES_TYPE == "4C5CE7CCD7124C448A82E65B965B36CC") {
                                        data[i].icon = layui.cache['contentPath'] + "/static/image/menud.png";
                                    } else if (data[i].RES_TYPE == "D0F4A751E3654AB3A714B8A0309D0BCB") {
                                        data[i].icon = layui.cache['contentPath'] + "/static/image/menu.png";
                                    } else if (data[i].RES_TYPE == "BB8C269F94114CAD8E0FFE530A404C64") {
                                        data[i].icon = layui.cache['contentPath'] + "/static/image/btn.png";
                                    } else if (data[i].RES_TYPE == "EB7113E02DA643D3B800A03ED2D87C09") {
                                        data[i].icon = layui.cache['contentPath'] + "/static/image/hidemenu.png";
                                    } else {
                                        data[i].icon = layui.cache['contentPath'] + "/static/image/tab.png";
                                    }
                                    if (data[i].BEIZ != "") {
                                        data[i].OBJNAME = data[i].OBJNAME + '(' + data[i].BEIZ + ')' + '-[' + data[i].RESTYPENAME + ']';
                                    } else {
                                        data[i].OBJNAME = data[i].OBJNAME + '-[' + data[i].RESTYPENAME + ']';
                                    }
                                }
                                return data;
                            }
                            else {
                                zlContext.errorMsg(responseData[msgName]);
                            }
                            return responseData;
                        }
                    }, {
                            onAsyncSuccess: zTreeOnAsyncSuccess
                        })
                }
            })
    }

    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var treeobj = $.fn.zTree.getZTreeObj(treeId),
            node = treeobj.getNodes();
        setInitAuthcheck(node);
        treeobj.refresh();
        layer.close(index);
    }
    function setInitAuthcheck(treenode) {
        for (var i = 0; i < treenode.length; i++) {
            var node = treenode[i];
            if (node.children != undefined) {
                setInitAuthcheck(node.children);
            }
            if (node.CHECKSTATE == 1) {
                node.checked = true;
            }
        }
    }

    $('#btnsave').on('click', function () {
        var selectnode = roletree.getSelectedNodes()
            , selectorgnode = orgtreeObj.getSelectedNodes()
            , autonode = authtree.getCheckedNodes()
            , coreauthlist = new Array();
        if (selectorgnode.length == 0) {
            zlContext.warnMsg('请先选择机构');
            return;
        }
        if (selectnode.length == 0) {
            zlContext.warnMsg('请先选择角色');
            return;
        }

        var ROLEID = selectnode[0].RWID
            , ORGID = selectorgnode.length == 0 ? "" : selectorgnode[0].RWID
            , CoreRightResLevel = {};
            CoreRightResLevel.ROLEID = ROLEID;
            CoreRightResLevel.ORGID = ORGID;
            coreauthlist.push(CoreRightResLevel);
        for (var i = 0; i < autonode.length; i++) {
            var node = autonode[i];
            CoreRightResLevel = {};
            CoreRightResLevel.ROLEID = ROLEID;
            CoreRightResLevel.ORGID = ORGID;
            CoreRightResLevel.RESID = node.RESID;
            CoreRightResLevel.CHECKSTATE = node.checked ? 1 : 0;            
            node.CHECKSTATE = CoreRightResLevel.CHECKSTATE;
            coreauthlist.push(CoreRightResLevel);
            authtree.updateNode(node);
        }

        zlContext.post(layui.cache['contentPath'] + "/manager/corerightreslevel/add", coreauthlist, function (data) {
            if (data.state == OK) {
                zlContext.successMsg("保存成功！");
            } else {
                zlContext.errorMsg(data.msg);
            }
        }
        );

    });
    $('#expand').on('click', function () {
        authtree.expandAll(true);
    });
    $('#unexpand').on('click', function () {
        authtree.expandAll(false);
    });
    $('#checkall').on('click', function () {
        authtree.checkAllNodes(true);
    })
    $('#uncheck').on('click', function () {
        var allnode = authtree.getNodes();
        setoppositecheck(allnode);
        authtree.refresh();
    });

    function setoppositecheck(treenode) {
        for (var i = 0; i < treenode.length; i++) {
            var node = treenode[i];
            if (node.children != undefined) {
                setoppositecheck(node.children);
            }
            if (node.checked) {
                node.checked = false;
            } else {
                node.checked = true;
            }
        }
    }

    $(window).on('resize', function () {
        zlContext.setMaxHeihgt(0);
        resizeFunction(32, 20, 365);
        var $dockingtopH = parseFloat($(".docking-top").height());
        var $dockingbottomH = parseFloat($(".docking-bottom").height());
        var $dockingfillH = parseFloat($(".docking-fill").height());
        if ($dockingtopH + $dockingbottomH > $dockingfillH) {
            $(".docking-fill").removeClass("docking-fill");
        } else {
            $(".docking-fill").addClass("docking-fill");
        }
    }).resize();

    // 窗口大小变化事件，filldeff用于求".docking-fill"元素的高差值，condeff用于求".zl-container"的高差值
    function resizeFunction(filldeff, condeff, tableheight) {
        var windowH = $(window).height(),
            zlcontainerH,
            topzltoolbar = $(".docking-top .zl-toolbar"),
            bottomzltoolbar = $(".docking-bottom .zl-toolbar"),
            dockingtopmb = parseFloat($(".docking-top").css("margin-bottom")),
            topzltoolbarH = topzltoolbar.height() + parseFloat(topzltoolbar.css("margin-bottom"));
            bottomzltoolbarH = bottomzltoolbar.height() + parseFloat(bottomzltoolbar.css("margin-bottom"));
        $(".docking-bottom").height(windowH - dockingtopmb - topzltoolbarH - tableheight - filldeff);
        $(".docking-bottom .zl-container").height($(".docking-bottom").height() - condeff - bottomzltoolbarH);
        return zlcontainerH = $(".docking-bottom").height() - condeff - bottomzltoolbarH;
    }

});